<?php

namespace app\api\controller;

use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Monitor extends Base
{
  /**
   * 推送服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function ssl_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|domain', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('ssl_monitor_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('ssl_monitor_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['check_time'] = (isset($vo['check_time']) && !empty($vo['check_time'])) ? date('Y-m-d H:i:s', $vo['check_time']) : '';
      $vo['is_expire'] = 0;
      $vo['expire_time'] = (isset($vo['expire_time']) && !empty($vo['expire_time'])) ? $vo['expire_time'] : 0;
      if (isset($vo['check_time']) && !empty($vo['check_time'])) {
        $vo['is_expire'] = ($vo['expire_time'] > time()) ? 1 : -1;
      }
      if ($vo['is_expire'] == 1 && $vo['expire_time']-time()<14*86400) {
        $vo['is_expire'] = 2;
      }
      $vo['domain_expire'] = '';
      if (isset($vo['check_time']) && !empty($vo['check_time']) && !empty($vo['expire_time']) && isset($vo['start_date']) && !empty($vo['start_date'])) {
        $vo['domain_expire'] = '起始:' . date('Y-m-d H:i:s', $vo['start_date']) . "\r\n截止:" . date('Y-m-d H:i:s', $vo['expire_time']);
      }
      $vo['start_date'] = (isset($vo['start_date']) && !empty($vo['start_date'])) ? date('Y-m-d H:i:s', $vo['start_date']) : '';
      $vo['expire_time'] = (isset($vo['expire_time']) && !empty($vo['expire_time'])) ? date('Y-m-d H:i:s', $vo['expire_time']) : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function site_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|domain', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('website_monitor_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('website_monitor_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['check_time'] = (isset($vo['check_time']) && !empty($vo['check_time'])) ? date('Y-m-d H:i:s', $vo['check_time']) : '';
      $vo['last_time'] = (isset($vo['last_time']) && !empty($vo['last_time'])) ? date('Y-m-d H:i:s', $vo['last_time']) : '';
      if ($vo['socket_type'] == 'http') {
        switch ($vo['ok_type']) {
          case 'resp_time':
            $vo['guize'] = '响应时间 ' . $this->changeCompareType($vo['compare_type']) . ' ' . $vo['ok_value'] . 'ms';
            break;
          case 'resp_status':
            $vo['guize'] = '状态码 ' . $this->changeCompareType($vo['compare_type']) . ' ' . $vo['ok_value'];
            break;
          case 'body':
            $vo['guize'] = 'body内容 ' . $this->changeCompareType($vo['compare_type']) . ' ' . $vo['ok_value'];
            break;
          case 'body_json':
            $vo['guize'] = 'body的json.code字段 ' . $this->changeCompareType($vo['compare_type']) . ' ' . $vo['ok_value'];
            break;
          default:
            $vo['guize'] = '未知';
            break;
        }
      } else if ($vo['socket_type'] == 'telnet') {
        $vo['guize'] = $vo['domain_port'];
      } else {
        $vo['guize'] = '';
      }
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function changeCompareType($type)
  {
    $list['dengyu'] = '等于';
    $list['xiaoyu'] = '小于';
    $list['xiaodengyu'] = '小于等于';
    $list['dayu'] = '大于';
    $list['dadengyu'] = '大于等于';
    return $list[$type];
  }
  public function ssl_monitor_log()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'ml_id' => input('param.ml_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where['uid'] = $this->uid;
    if (!empty($data['ml_id'])) {
      $where['ml_id'] = trim($data['ml_id']);
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('ssl_monitor_log')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('ssl_monitor_log')->where($where)->count('_id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function website_monitor_log()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'ml_id' => input('param.ml_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where['uid'] = $this->uid;
    if (!empty($data['ml_id'])) {
      $where['ml_id'] = trim($data['ml_id']);
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('website_monitor_log')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('website_monitor_log')->where($where)->count('_id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  /**
   * 编辑SSL监控
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function edit_ssl_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'domain|监控域名'  => 'require',
        'ps_id|监控通知配置'  => 'require',
        'status|监控状态'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'domain' => input('param.domain', '', 'trim'),
        'ps_id' => input('param.ps_id', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('ssl_monitor_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'ssl_monitor_num', '监控SSL证书数量', $limitCount);
      $data['status'] = intval($data['status']);
      // if (substr($data['domain'], 0, 4) != 'http') {
      //   $data['domain'] = 'http://'. $data['domain'];
      // }
      $parseUrl = parse_url($data['domain']);
      $data['domain'] = (isset($parseUrl['host']) && !empty($parseUrl['host']))? $parseUrl['host']: $data['domain'];
      if (!empty($data['id'])) {
        $hasInfo = Db::connect('mongodb')->name('ssl_monitor_list')->where('_id', $data['id'])->find();
        if (empty($hasInfo)) {
          return json(['code' => -1, 'data' => '', 'msg' => '配置不存在']);
        }
        if ($data['domain'] != $hasInfo['domain']) {
          $data['check_time'] = 0;
          $data['expire_time'] = 0;
          $data['error'] = '';
        }
        $status = Db::connect('mongodb')->name('ssl_monitor_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        $hasInfo = Db::connect('mongodb')->name('ssl_monitor_list')->where('domain', $data['domain'])->find();
        if (!empty($hasInfo)) {
          return Result::Error($data['domain'].' 已存在');
        }
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('HM');
        $status = Db::connect('mongodb')->name('ssl_monitor_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('ssl_monitor_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_site_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'domain|监控域名'  => 'require',
        'ps_id|监控通知配置'  => 'require',
        'status|监控状态'  => 'require',
        // 'request_type|请求类型'  => 'require',
        'reate|监控频率'  => 'require',
        // 'ok_type|条件类型'  => 'require',
        // 'compare_type|操作符'  => 'require',
        // 'ok_value|条件值'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'domain' => input('param.domain', '', 'trim'),
        'ps_id' => input('param.ps_id', '', 'trim'),
        'request_type' => input('param.request_type', '', 'trim'),
        'ok_type' => input('param.ok_type', '', 'trim'),
        'compare_type' => input('param.compare_type', '', 'trim'),
        'ok_value' => input('param.ok_value', '', 'trim'),
        'reate' => input('param.reate', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'socket_type' => input('param.socket_type', 'http', 'trim'),
        'domain_port' => input('param.domain_port', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('website_monitor_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'site_monitor_num', '监控网站数量', $limitCount);
      $data['status'] = intval($data['status']);
      $data['reate'] = intval($data['reate']);
      if ($data['reate'] == 1 && intval($this->user['version']) != 3) {
        return json(['code' => -1, 'data' => '', 'msg' => '当前会员版本暂不支持监控频率为1分钟的监控']);
      }
      if ($data['ok_type'] == 'resp_time' && $data['ok_value'] > 2000) {
        return Result::Error('响应时间不得超过2000ms');
      }
      $data['last_time'] = strtotime(date('Y-m-d H:i') . ':00') + intval($data['reate']) * 60;
      $data['ok_value'] = (is_numeric($data['ok_value'])) ? intval($data['ok_value']) : $data['ok_value'];
      $data['request_status'] = 2;
      $data['check_status'] = 2;
      if (!empty($data['id'])) {
        $hasInfo = Db::connect('mongodb')->name('website_monitor_list')->where('_id', $data['id'])->find();
        if (empty($hasInfo)) {
          return json(['code' => -1, 'data' => '', 'msg' => '配置不存在']);
        }
        // unset($data['domain']);
        $status = Db::connect('mongodb')->name('website_monitor_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('HM');
        $status = Db::connect('mongodb')->name('website_monitor_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('website_monitor_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del_ssl()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('ssl_monitor_list')->where('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('ssl_monitor_log')->where('ml_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_ssl_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('ssl_monitor_list')->whereIn('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('ssl_monitor_log')->whereIn('ml_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_site_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('website_monitor_list')->whereIn('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('website_monitor_log')->whereIn('ml_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_site()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('website_monitor_list')->where('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('website_monitor_log')->where('ml_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
}
